#!/usr/bin/env bash
# This script requires fastmod to be installed
# fastmod: https://github.com/facebookincubator/fastmod


main() {
    NEW_VERSION="$1"

    if [ -z "$NEW_VERSION" ]; then
        NEW_VERSION=$(awk -F'[".]' '/^version = / {print $2 "." ($3+1) ".0"}' Cargo.toml)
        if [ -z "$NEW_VERSION" ]; then
            echo "Error: Could not determine current version from workspace Cargo.toml"
            exit 1
        fi
        
        echo "Auto-incrementing to $NEW_VERSION"
    fi

    echo "Checking out master branch..."
    if ! git checkout master; then
        echo "Error: Failed to checkout master branch"
        exit 1
    fi

    echo "Creating new release branch: release-$NEW_VERSION"
    git checkout -b "release-$NEW_VERSION"
    echo "updating version to '$NEW_VERSION'..."
    fastmod --accept-all '^version = ".*"' 'version = "'$NEW_VERSION'"' Cargo.toml
    fastmod --accept-all '(squawk-[a-z_]+ = \{ path = "[^"]+", )version = "[^"]+"' '${1}version = "'$NEW_VERSION'"' Cargo.toml
    fastmod --accept-all -m '(name = "squawk"\n)version = ".*?"' '${1}version = "'$NEW_VERSION'"' Cargo.lock
    fastmod --accept-all '"version": ".*"' '"version": "'$NEW_VERSION'"' package.json
    fastmod --accept-all '"version": ".*"' '"version": "'$NEW_VERSION'"' squawk-vscode/package.json
    fastmod --accept-all -m '(pname = "squawk";.*?)version = ".*?"' '${1}version = "'$NEW_VERSION'"' flake.nix
    fastmod --accept-all 'const SQUAWK_USER_AGENT: &str = "squawk/.*"' 'const SQUAWK_USER_AGENT: &str = "squawk/'$NEW_VERSION'"' crates/squawk_github/src/app.rs
    
    echo "Updating CHANGELOG.md..."
    CURRENT_DATE=$(date +"%Y-%m-%d")
    sed -i '' "s/^## \[Unreleased\]$/## [Unreleased]\n\n## v$NEW_VERSION - $CURRENT_DATE/" CHANGELOG.md
    
    echo "Opening CHANGELOG.md for editing..."
    ${EDITOR:-vi} CHANGELOG.md
}


main "$@"
